package com.swsc.xapp.activity.mainActivity.presenter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;

import com.swsc.xapp.activity.mainActivity.MyMainHandler;
import com.swsc.xapp.enums.NJSFConsts;
import com.swsc.xapp.utils.CameraUtils;
import com.swsc.xapp.utils.ConstantUils;
import com.swsc.xapp.utils.ImageUtils;
import com.swsc.xapp.utils.MessageInfoUtils;

import com.swsc.xapp.utils.httpUtil.HttpRequestUtils;
import com.swsc.xapp.utils.httpUtil.ImageHttpUtils;
import com.swsc.xapp.utils.httpUtil.NetWorkUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

/**
 * @author YH_CK
 * data 2018.09.13 17:12
 * describe
 **/
public class MainPresenterCompl implements IMainPresenter {

    private final String TAG = MainPresenterCompl.class.getSimpleName();




    private HttpRequestUtils mHttpRequestUtils;
    private MessageInfoUtils mMessageInfoUtils;
    private Context mContext;
    private MyMainHandler myMainHandler;

    public MainPresenterCompl(Context context, String path, MyMainHandler handler) {
        this.mContext = context;
        this.myMainHandler = handler;
        this.mHttpRequestUtils = HttpRequestUtils.getInstance(context);
        mMessageInfoUtils = MessageInfoUtils.getInstance(mContext);
    }

    /**
     * 拨打电话
     *
     * @param jsonData data
     */
    @SuppressLint("MissingPermission")
    @Override
    public void callPhone(String jsonData) {
        String phone = "";

        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            phone = jsonObject.getString("telphone");
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }






    /**
     * 打开系统相机
     */
    @Override
    public void openSystemCamera(Integer code) {

        if(null == code){
            ImageUtils.openCameraGetPhoto(mContext);
        }else {
            CameraUtils.openCameraGetPhoto(mContext, NJSFConsts.CODE_OPEN_CAMERA);
        }
    }

    @Override
    public void openSystemCamera(Integer code, String bucket) {

        if(null == code){
            ImageUtils.openCameraGetPhoto(mContext, bucket);
        }else {
            CameraUtils.openCameraGetPhoto(mContext, NJSFConsts.CODE_OPEN_CAMERA, bucket);
        }
    }
    /**
     * 检查网络是否可用
     *
     * @param params string
     */
    @Override
    public void checkNetWorkAvailable(String params) {
        String checkURL = "https://www.baidu.com/";
        try {
            JSONObject jsonObject = new JSONObject(params);
            checkURL = jsonObject.getString("host_name");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        final JSONObject result = new JSONObject();

        NetWorkUtils.isNetWorkAvailableOfGet(checkURL, new Comparable<Boolean>() {
            String mStatus;

            @Override
            public int compareTo(Boolean available) {
                if (available) {
                    // 设备访问Internet正常
                    mStatus = "1000";
                } else {
                    //设备无法访问Internet
                    mStatus = "9999";
                }
                try {
                    result.put("status", mStatus);
                    callBackHandler(ConstantUils.JS_FUNCTION_CHECK_NETWORK_FLAG, result.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return 0;
            }

        });
    }

    /**
     * 获取短信信息
     */
    @Override
    public void getSmsInfo() {
        String resultJson = mMessageInfoUtils.getSmsInfo();
        if (resultJson != null) {
            callBackHandler(ConstantUils.JS_FUNCTION_SMS_FLAG, resultJson);
        }
    }


    /**
     * 打开系统相机
     */
    @Override
    public void openSystemPhotoAlbum() {
        Intent intent;
        intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        ((Activity) mContext).startActivityForResult(intent, ConstantUils.FILE_SELECT_BY_ALBUM_CODE);
    }


    /**
     * HTTP请求，获取数据
     *
     * @param data data
     */
    @Override
    public void httpPostGetData(String data) {
        String url = "";//请求地址
        String headerData = "";//请求头
        String paramBody = "";//请求数据
        try {
            JSONObject jsonObject = new JSONObject(data);
            url = jsonObject.getString("url");
            headerData = jsonObject.getString("header");
            paramBody = jsonObject.getString("params");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mHttpRequestUtils.setAuthHeader(headerData);
        mHttpRequestUtils.postDataAsynToNet(url, paramBody, new HttpRequestUtils.MyNetCall() {
            @Override
            public void success(Call call, Response response) throws IOException {
                if (response.code() == 200) {
                    try {
                        JSONObject jsonData = new JSONObject(response.body().string());
//                        System.out.println(jsonData.toString());
                        callBackHttpData(jsonData.toString(), "");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    callBackHttpData("", response.toString());
                }
            }

            @Override
            public void failed(Call call, IOException e) {
                callBackHttpData("", e.toString());
            }
        });
    }

    /**
     * 请求接口返回数据
     *
     * @param result string
     */
    private void callBackHttpData(String result, String errorMeaasge) {
        JSONObject jsonObject = new JSONObject();
        if (result != null && !"".equals(result)) {
            try {
                JSONObject getJsonObject = new JSONObject(result);
                jsonObject.put("status", "1000");
                jsonObject.put("data", getJsonObject);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            try {
                jsonObject.put("status", "4001");
                jsonObject.put("data", "");
                jsonObject.put("errorMeaasge", errorMeaasge);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Message message = new Message();
        message.what = 1001;
        Bundle bundle = new Bundle();
        bundle.putString("key", ConstantUils.JS_FUNCTION_HTTP_REQUEST_FLAG);
        bundle.putString("jsonData", jsonObject.toString());
        message.setData(bundle);
        myMainHandler.sendMessage(message);
    }

    //判断是否有获取联系人的权限
    public void returnPermissionState(boolean has) {
        JSONObject js = new JSONObject();
        try {
            if (has) {
                js.put("status", "1000");
            } else {
                js.put("status", "3001");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        callBackHandler(ConstantUils.JS_FUNCTION_SEARCH_CONTACTS_FLAG, js.toString());
    }


    /**
     * 暂时废弃
     */
    class MyAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String result;
            if (params == null || params.length == 0) {
                return "";
            }
            ImageHttpUtils mNetWorkutils = ImageHttpUtils.getInstance();
            result = mNetWorkutils.updateFilePostConn(params[0].toString());
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            JSONObject jsonObject = new JSONObject();
            if (result != null && !"".equals(result)) {
                try {
                    JSONObject getJsonObject = new JSONObject(result);
                    jsonObject.put("status", "1000");
                    jsonObject.put("data", getJsonObject);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    jsonObject.put("status", "4001");
                    jsonObject.put("data", "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            Message message = new Message();
            message.what = 1001;
            Bundle bundle = new Bundle();
            bundle.putString("key", ConstantUils.JS_FUNCTION_UPDATE_IMAGE_FLAG);
            bundle.putString("jsonData", jsonObject.toString());
            message.setData(bundle);
            myMainHandler.sendMessage(message);
        }
    }

    /**
     * 发送JS回调
     *
     * @param key        key
     * @param resultJson json内容
     */
    public void callBackHandler(String key, String resultJson) {
        Message message = new Message();
        message.what = 1001;
        Bundle bundle = new Bundle();
        bundle.putString("key", key);
        bundle.putString("jsonData", resultJson);
        message.setData(bundle);
        myMainHandler.sendMessage(message);
    }

    /*
     * check Permission
     * */
    public void checkPermissionHandler(int requestCode, int messageCode, String permissionName) {
        Message message = new Message();
        message.what = 1010;
        Bundle bundle = new Bundle();
        bundle.putInt("requestCode", requestCode);
        bundle.putInt("messageCode", messageCode);
        bundle.putString("permission", permissionName);
        message.setData(bundle);
        myMainHandler.sendMessage(message);
    }

    /**
     * 上传图片
     *
     * @param data jsonObject
     */
    @Override
    public void mUpdateImage(String data) {
        //  new MyAsyncTask().execute(data);
        //TODO 2018:上次修改成OKHTTP框架
        mHttpRequestUtils.updateFile(data, new HttpRequestUtils.MyNetCall() {
            @Override
            public void success(Call call, Response response) throws IOException {
                if (response.code() == 200) {
                    try {
                        JSONObject jsonData = new JSONObject(response.body().string());
                        setUpdateImageData(jsonData.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void failed(Call call, IOException e) {
                setUpdateImageData("");

            }
        });
    }

    private void setUpdateImageData(String result) {
        JSONObject jsonObject = new JSONObject();
        if (result != null && !"".equals(result)) {
            try {
                JSONObject getJsonObject = new JSONObject(result);
                jsonObject.put("status", "1000");
                jsonObject.put("data", getJsonObject);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            try {
                jsonObject.put("status", "4001");
                jsonObject.put("data", "");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Message message = new Message();
        message.what = 1001;
        Bundle bundle = new Bundle();
        bundle.putString("key", ConstantUils.JS_FUNCTION_UPDATE_IMAGE_FLAG);
        bundle.putString("jsonData", jsonObject.toString());
        message.setData(bundle);
        myMainHandler.sendMessage(message);
    }
}
